package xyz.xtt.schedule.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import lombok.extern.slf4j.Slf4j;
import xyz.xtt.common.starter.cache.CacheManager;
import xyz.xtt.common.starter.cache.GlobalTableCache;
import xyz.xtt.schedule.entity.AssetTransactionEntity;
import xyz.xtt.schedule.mapper.asset.AssetTransactionMapper;

/**
 * @author wangqi
 */
@RefreshScope
@Service
@Slf4j
public class AssetTransactionService extends ServiceImpl<AssetTransactionMapper, AssetTransactionEntity> {
	@Autowired
	AssetExtService assetExtService;
	@Autowired
	private CacheManager cacheManager;

	public void updateHashByOrderId(AssetTransactionEntity entity, String hash) {
		UpdateWrapper<AssetTransactionEntity> updateWrapper = new UpdateWrapper<>();
		updateWrapper.eq("order_id", entity.getOrderId()).set("deal_hash", hash);
		int update = baseMapper.update(updateWrapper);
		if (update > 0) {
			// 清埋缓存
			cacheManager.delete(GlobalTableCache.TBL_ASSET_TRANSACTION, entity.getGoodsId());
		}
	}

	public void updateTransactionChainHash(String orderId, String blockNum, int createDateTime) {
		UpdateWrapper<AssetTransactionEntity> updateWrapper = new UpdateWrapper<>();
		updateWrapper.eq("order_id", orderId).set("deal_block_num", blockNum).set("up_chain_datetime", createDateTime);
		int update = baseMapper.update(updateWrapper);
		if (update > 0) {
			AssetTransactionEntity assetTransactionEntity = findByOrderId(orderId);
			// 清埋缓存
			cacheManager.delete(GlobalTableCache.TBL_ASSET_TRANSACTION, assetTransactionEntity.getGoodsId());
		}
	}

	/**
	 * 查询待转移的数字资产
	 */
	public List<AssetTransactionEntity> findTransferList() {
		return baseMapper.findTransferList();
	}

	/**
	 * 查询待销毁的数字资产
	 */
	public List<AssetTransactionEntity> findBurnList() {
		return baseMapper.findBurnList();
	}

	/**
	 * 查询符合要更新链交易信息列表 匹配不是索引，弃用
	 */
	@Deprecated
	public List<AssetTransactionEntity> findUpdateChainInfoList() {
		QueryWrapper<AssetTransactionEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.isNotNull("deal_hash");
		queryWrapper.isNull("deal_block_num");
		return list(queryWrapper);
	}

	/**
	 * 根据order_id查询是否存在记录
	 */
	public AssetTransactionEntity findByOrderId(String orderId) {
		QueryWrapper<AssetTransactionEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("order_id", orderId);
		return baseMapper.selectOne(queryWrapper);
	}
}
